<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="socket.io.js"></script>
    <title>Chat Room Demo</title>
</head>

<body>
    <h1>Chat Room Based on Socket.io</h1>
    SEND:
    <input type="text" id="sendText" />
    <button id="sendBtn">Send</button>
    <br /> RECV：
    <span id="recv"></span>
    <script>
        var socket = io("ws://localhost:8001/")
        function showMsg(str, type) {
            var div = document.createElement('div');
            div.innerHTML = str
            if (type == "enter") {
                div.style.color = 'blue';
            } else if (type == "disconnect") {
                div.style.color = 'red';
            }
            document.body.appendChild(div);
        }

        document.getElementById("sendBtn").onclick = function () {
            var txt = document.getElementById("sendText").value;
            if (txt) {
                socket.emit('message', txt);
            }
        }

        socket.on('enter', function (data) {
            showMsg(data, 'enter');
        });

        socket.on('message', function (data) {
            showMsg(data, 'message');
        });

        socket.on('disconnect', function (data) {
            showMsg(data, 'disconnect');
        });
    </script>
</body>

</html>